package utils

import (
	"fmt"
	"math"
	"strconv"
)

func ParseInt(v interface{}) (rt int, err error) {
	switch i := v.(type) {
	case int:
		rt = i
	case string:
		rt, err = strconv.Atoi(i)
	case float64:
		rt = int(math.Round(i))
	case float32:
		rt = int(math.Round(float64(i)))
	case int64:
		rt = int(i)
	case int32:
		rt = int(i)
	}
	return
}

func ParseInt64(v interface{}) (rt int64, err error) {
	switch i := v.(type) {
	case int:
		rt = int64(i)
	case string:
		rt, err = strconv.ParseInt(i, 10, 64)
	case float64:
		rt = int64(math.Round(i))
	case float32:
		rt = int64(math.Round(float64(i)))
	case int64:
		rt = i
	case int32:
		rt = int64(i)
	}
	return
}

func ParseIntOrDefault(v interface{}, defaultValue int) (rt int) {
	result, err := ParseInt(v)
	if err == nil {
		return result
	}
	return defaultValue
}

func ParseInt64OrDefault(v interface{}, defaultValue int64) (rt int64) {
	result, err := ParseInt64(v)
	if err == nil {
		return result
	}
	return defaultValue
}

func ParseFloat64(v interface{}) (rt float64, err error) {
	switch i := v.(type) {
	case int:
		rt = float64(i)
	case string:
		rt, err = strconv.ParseFloat(i, 64)
	case float64:
		rt = i
	case float32:
		rt = float64(i)
	}
	return
}

func ParseString(v interface{}) string {
	return fmt.Sprintf("%v", v)
}
